package com.xywy.wjk.fragment;


import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xywy.R;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.bean.BloodPresureDataFromServer;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.util.CalendarUtil;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MD5Util;
import com.xywy.common.util.MLog;
import com.xywy.common.util.StringUtils;
import com.xywy.common.util.ble.common.CommonAttr;
import com.xywy.common.util.ble.util.BLEBloodPresureProvider;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.fwc.net.StringParser;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.AddDevicesActivity;
import com.xywy.wjk.BloodPressureDetailActivity;
import com.xywy.wjk.WjkActivity;
import com.xywy.wjk.WjkFragment;
import com.xywy.wjk.bean.BloodPressureData;
import com.xywy.wjk.dao.BloodPressureDataDao;
import com.xywy.wjk.dao.WeightDataDao;
import com.xywy.wjk.dao.BloodPressureDataDao.Properties;
import com.xywy.wjk.util.BloodPresureCommon;
import com.xywy.wjk.util.DeviceState;
import com.xywy.wjk.util.WjkConstant;
import com.xywy.wjk.widget.BloodPresureView;
import com.xywy.wjk.widget.TipDialog;
import com.xywy.wjk.widget.TipDialog.OkayListener;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * 血压
 * 
 * @author wangwenlong
 */
@SuppressLint("NewApi")
public class BloodPressureFragment extends Fragment implements OnClickListener {
	private static final long SCAN_PERIOD = 15 * 1000;
	private static final String TAG = "BloodPressureFragment";

	private BLEBloodPresureProvider utils; // 蓝牙工具类
	private BluetoothAdapter mBluetoothAdapter;// 蓝牙适配器。
	private BluetoothGattCharacteristic info_Characteristic; // 设备信息通道（获取SystemID）
	private BluetoothGattService infoDataService; // 设备服务
	private BluetoothGattService swapDataService;
	private BluetoothGattCharacteristic send_Characteristic;
	private BluetoothGattCharacteristic rece_Characteristic;
	private BloodPressureDataDao bloodPressureDataDao; // 数据库处理

	private String wjkAddcontent; // 微健康中添加的数据
	private Button btn_start_measure;
	private TextView tv_tip; // 血压文字提示
	private TextView tv_connect_state; //
	private ImageView iv_unopen_big;
	private BloodPresureView bpv; // 自定义控件，我们的血压柱
	private boolean mBloodConnectStatus = false;// 血压计连接状态

	byte[] broadCastData;// 存储当前从设备返回数据的数组
	
	private LinearLayout ll_not_connectted_prompot;

	/* 蓝牙设备需要的变量 */

	private TextView messageTime;
	private String userid;
	
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			getResult(CommonAttr.Sphygmomanometer.GET_REUSLT);
		};
	};
	private SharedPreferences sp;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.blood_fragment, null);
		
		sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(getActivity()).getUserid();
		this.initDAO();
		initView(view);
		this.preInit();
		this.initDAO();
		this.onclick();
		this.initBLE();
		return view;
	}

	/* 初始化控件 */
	private void initView(View view) {

		// btn_start_measure = (Button)
		// view.findViewById(R.id.btn_start_measure);
		tv_tip = (TextView) view.findViewById(R.id.tv_tip);
		iv_unopen_big = (ImageView) view.findViewById(R.id.iv_unopen_big);
		tv_connect_state = (TextView) view.findViewById(R.id.tv_connect_state);
		initBloodPresureView(view);
		messageTime = (TextView) view.findViewById(R.id.messageTime);
		ll_not_connectted_prompot = (LinearLayout) view.findViewById(R.id.ll_not_connectted_prompot);
//		registerDBobserver();
		ll_not_connectted_prompot.setOnClickListener(this);
		iv_unopen_big.setVisibility(View.GONE);
	}

	/**
	 * 初始化血压计自定义控件
	 * 
	 * @param view
	 */
	private void initBloodPresureView(View view) {
		bpv = (BloodPresureView) view.findViewById(R.id.bpv);
		bpv.setActivity(getActivity());
		bpv.setBtnOnClickListener(btnl);
		bpv.setLlOnClickListener(lll);
		
		bpv.setBtnText("开始测量");
		bpv.setBtnState(false);
	}

	/* 初始化DAO */
	private void initDAO() {
		BaseDao baseDao = BaseDao.getInstance(getActivity());
		bloodPressureDataDao = baseDao.getBloodPressureDataDao();
	}

	/* 点击 */
	private void onclick() {
		tv_tip.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.tv_tip:
			// connectDevice();
			break;
		case R.id.barChartLayout:
			Intent intent = new Intent(getActivity(), BloodPressureDetailActivity.class);
			startActivity(intent);
			break;
		case R.id.ll_not_connectted_prompot:
			scanLeDevice(true, "KBB");
			break;

		}
	}

	/**
	 * 自定义控件中按钮点击事件
	 */
	OnClickListener btnl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			if (mBloodConnectStatus) {
				bpv.setTestResult("");
//				bpv.setBtnText("正在测量中");
				System.out.println("l.onClick()");
				starttest(CommonAttr.Sphygmomanometer.START_MEASURE);
				FragmentMainActivity.CANTOUCH = false;
				bpv.setHightAndLowNum(0, 0);
				// WWL
				// bpv.startPresure();
				bpv.setBtnState(false);
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						isGetResult = true;
						getResult(CommonAttr.Sphygmomanometer.GET_REUSLT);
					}
				}, 1000);
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (broadCastData == null || broadCastData.length < 1) {
							// 已经过了5秒钟没有获取数据，让按钮可以再次点击
							bpv.setBtnState(true);
							FragmentMainActivity.CANTOUCH = true;
						}
					}
				}, 5000);
			} else {
				Toast.makeText(getActivity(), "血压计连接失败 请重新连接", Toast.LENGTH_SHORT).show();
			}

		}
	};
	/**
	 * 血压柱形图的点击事件
	 */
	OnClickListener lll = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(getActivity(), BloodPressureDetailActivity.class);
			startActivity(intent);
		}
	};

	/**
	 * 初始化蓝牙配置
	 */
	private void initBLE() {
		utils = BLEBloodPresureProvider.getInstance();
		utils.init(getActivity());
		mBluetoothAdapter = utils.getBLEAdatper();
	}


	/**
	 * 设置最后的测试结果
	 */
	private void setLastDataOnBPV() {
		List<BloodPressureData> datas = getLastData();
		if (datas != null && datas.size() > 0) {
			BloodPressureData data = datas.get(0);
			bpv.setHightAndLowNum(data.getHighPressure(), data.getLowPressure());
			bpv.setTestResult(BloodPresureCommon.getTestResult(data.getHighPressure(), data.getLowPressure()));
			messageTime.setText(CalendarUtil.getDiffTime(data.getDate()));
		}
	}


	TipDialog dialog;
//	private String userid;

	/**
	 * 数据加载
	 */
	private void preInit() {
		dialog = new TipDialog(getActivity(), TipDialog.VIEW_LOADING, mhander);

		// 添加页面数据
		String addContent = getWjkAddcontent();
		if (!StringUtils.isNull(addContent)) {
			MLog.i("fdfsa", "添加页面返回的数据:" + addContent);
		}
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				setLastDataOnBPV();
			}
		});
	}

	Handler mhander = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case BloodPresureView.REFRESH_VIEW:
				bpv.haha();
				break;
			case TipDialog.DIALOG_TIMER_CANCLE:
				if (!mBloodConnectStatus) {
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							stateFail();
						}
					});
				}
			
				break;

			default:
				break;
			}
		};
	};
	String startName;

	/**
	 * 扫描功能
	 * 
	 * @param enable
	 *            true 开始扫描， false 停止扫描
	 * 
	 */
	public void scanLeDevice(final boolean enable, String startName) {

		if (utils == null) {
			initBLE();
		}
		if (!mBluetoothAdapter.isEnabled()) {
			unOpenBleTip();
			return;
		}

		stateScaning();
		this.startName = startName;
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mhander.postDelayed(new Runnable() {
				@Override
				public void run() {
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					if (!mBloodConnectStatus) {
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								stateFail();
							}
						});
					}
				}
			}, SCAN_PERIOD);
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	public final String DEVICE_BLOOD_PAUSERE = "blood_pausere"; // 血压计
	
	private boolean is_connect = false;
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			if (null != device.getName() && device.getName().startsWith(startName)) {
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if(!is_connect){
							is_connect = true;
							mBluetoothAdapter.stopLeScan(mLeScanCallback);
							connectDevice(device.getAddress());
						}
					}
				});
			}
		}
	};

	/**
	 * 开始连接设备方法，此处直接从本地取出之前连接过的设备MAC 调用gatt连接方法；
	 */
	public void connectDevice(String curAddress) {
		if (utils.getConnectState() == BluetoothProfile.STATE_CONNECTED) {
			utils.disconnect();
			// utils.close();
		}
		if (null != curAddress && curAddress.length() > 0) {
			utils.connect(curAddress);
		} else {
			// 并没有连接过当前体重设备。点击跳转到设备添加页面；
			Intent intent = new Intent(getActivity(), AddDevicesActivity.class);
			startActivityForResult(intent, ResultCode.SUCCESS);
			Toast.makeText(getActivity(), "您尚未连接过当前设备，请先添加设备！", Toast.LENGTH_LONG).show();
			stateFail();
		}

	}


	/*
	 * 和蓝牙设备进行交互的广播
	 */
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
//		private boolean mConnected;

		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BLEBloodPresureProvider.ACTION_GATT_CONNECTED.equals(action)) {
				// 连接时
				Log.d("BLOODPRESURE-------", "连接成功");
				j = 0;
				mBloodConnectStatus = true;
				getActivity().runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Log.d("BLOODPRESURE", "连接到血压计后，置0");
						bpv.setHightAndLowNum(0, 0);
						stateSuc();
					}
				});
			} else if (BLEBloodPresureProvider.ACTION_GATT_DISCONNECTED.equals(action)) {// 断开连接时
//				mConnected = false;
				mBloodConnectStatus = false;
				stateFail();
			} else if (BLEBloodPresureProvider.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
				/* 可以获取所有的通道 */
				getGattCharacteristics();
			} else if (BLEBloodPresureProvider.ACTION_WRITE_DATA_AVAILABLE.equals(action)) {
				Log.d("BloodPressureFragment", "write----");
				read();
			} else if (BLEBloodPresureProvider.ACTION_DATA_AVAILABLE.equals(action)) {
				Log.d("BloodPressureFragment", "heihei");

			} else if (BLEBloodPresureProvider.ACTION_XUEYA_DATA.equals(action)) {
				// TODO 从通道中读取数据；

				broadCastData = intent.getByteArrayExtra(BLEBloodPresureProvider.EXTRA_DATA);
				if (broadCastData == null || broadCastData.length < 8) {
					return;
				}
				// 本次回传的数据是：EB 21 80 00 30 00 00 00 00 00 00 44 EB --- 6,7收缩压
				float heightPress = getdata(broadCastData[5], broadCastData[6]);
				float lowPress = getdata(broadCastData[7], broadCastData[8]);
				float heartRate = getdata(broadCastData[9], broadCastData[10]);
				Log.d(TAG, "高压：" + heightPress);
				Log.d(TAG, "低压：" + lowPress);
				Log.d(TAG, "心率：" + heartRate);
				Log.d(TAG, "袖带压力：" + getdata(broadCastData[3], broadCastData[4]));
				Log.d(TAG, "接收到的数据为： " + broadCastData);
				float bondPress = getdata(broadCastData[3], broadCastData[4]);
//				if (heightPress != 0 && lowPress != 0)
//					bpv.setHightAndLowNum(heightPress, lowPress);
//				else 
				Log.d("BLOODPRESURE", String.format("%02X ", broadCastData[2]));
				if (broadCastData[2] == (byte) 0x80) {
					// 正在测量；
					if (!FragmentMainActivity.CANTOUCH)
						bpv.setHightAndLowNum(bondPress, bondPress);
					FragmentMainActivity.CANTOUCH = false;
					Log.d("BLOODPRESURE", "正在测量中");
				} else {
					// 没有测量||测量结束；
					j++;
					if (j >= 3) {
						FragmentMainActivity.CANTOUCH = true;
						if (lowPress == 0 || heightPress == 0) {
							Toast.makeText(getActivity(), "本次测量结果为0，请您重新测量", Toast.LENGTH_SHORT).show();
							// setLastDataOnBPV();
							bpv.setHightAndLowNum(0, 0);
							bpv.setTestResult("测量失败,请重试");
							stoptest(CommonAttr.Sphygmomanometer.STOP_MEASURE); // 停止测试
							isGetResult = false; // 不在执行获取结果方法
							bpv.setBtnText("开始测量");
							if (mBloodConnectStatus)
								bpv.setBtnState(true);
							if (j >= 10)
								Toast.makeText(getParentFragment().getActivity(), "当前蓝牙不稳定。", Toast.LENGTH_SHORT).show();
							return;
						}
						Log.d("BLOODPRESURE", "血压测试结束，heightPress" + heightPress + "lowPress：" + lowPress);
						if (heightPress != 0 && lowPress != 0)
						bpv.setHightAndLowNum(heightPress, lowPress);
						isGetResult = false;// 停止时时获取当前测量结果；
						if(heightPress>0 && lowPress>0)
						bpv.setTestResult(BloodPresureCommon.getTestResult(heightPress, lowPress)); // 将当前结果展示在View上；
						bpv.setBtnText("开始测量");
						messageTime.setText(CalendarUtil.getDiffTime(System.currentTimeMillis()));
						bpv.setBtnState(true);
						j = 0;
						// 将获取结果存入数据库；
						if (heartRate > 0 && heightPress > 0 && lowPress > 0)
							insertData(heartRate, heightPress, lowPress, "State", "temp_automactily_device_identify", "temp_handly_device_identify", System.currentTimeMillis());
					}
				}
				if ((broadCastData[2] & (byte) 0x40) != 0) {
					// 测量数值有效；
				} else if ((broadCastData[2] & (byte) 0x40) == 0x40) {
					// 测量数值无效；
				}

			}
		}

		/**
		 * 处理16进制数据
		 * 
		 * @param data
		 * @return
		 */
		private float getdata(byte... data) {
			BigInteger bigNum = new BigInteger(data);
			float intNum = Float.parseFloat(bigNum.intValue() + "");
			return intNum;
		}
	};
	int j = 0;
	private BloodPressureData bloodPressureData;
	private final String sort = "xueya";

	/**
	 * 将数据上传到服务器
	 * 
	 * @param data
	 */
	private String secret_key = "213aBc$l;@13";

//	private void uploadDataToServer(BloodPressureData data) {
//		data.setDate(data.getDate() / 1000);
//		HashMap<Object, Object> params = new HashMap<Object, Object>();
//		params.put("app_username", "xywy_tizhong");
//		String userid = sp.getString("userid", "");
//		params.put("xywy_userid", userid);
//		params.put("sort", sort);
//		// -------------------
//		String dataStr = "["+turn2ServerJsonData(data, userid)+"]";
//		params.put("data", dataStr);
//		System.out.println(dataStr);
//		params.put("datatime", System.currentTimeMillis() / 1000);
//		// -------------------
//		String sn = secret_key + userid + sort + dataStr + "xywy_tizhong";
//		try {
//			params.put("sn", MD5Util.md5(sn));
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//		Request.postData(new MyPaser(data), new DataCallBack<String>() {
//
//			@Override
//			public void dataCall(String str) {
//				System.out.println("上传本次记录的返回值" + str);
//			}
//		}, "http://api.yun.xywy.com/index.php/api/setdata/data_all/", params);
//
//	}

	/**
	 * 将数据库中提取出来的数据转换成服务器的been
	 * 
	 * @param data
	 */
	private String turn2ServerJsonData(BloodPressureData data, String userID) {
		Gson gson = new Gson();
		BloodPresureDataFromServer dataFormServer = new BloodPresureDataFromServer();
		dataFormServer.setApp_data(data.getDevice_id());
		dataFormServer.setApp_user_id("");
		dataFormServer.setDatatime(data.getDate());// 时间上面已经处理
		dataFormServer.setHeart(data.getHeartRate());
		dataFormServer.setHigh(data.getHighPressure());
		dataFormServer.setLow(data.getLowPressure());
		dataFormServer.setShou_data(data.getHand_str());
		dataFormServer.setXywy_userid(userID);
		return gson.toJson(dataFormServer);
	}

//	class MyPaser extends BaseParser<String> {
//
//		BloodPressureData data;
//
//		MyPaser(BloodPressureData data2) {
//			this.data = data2;
//		}
//
//		@Override
//		public String parseJson(String result) {
//			try {
//				JSONObject jsonObject = new JSONObject(result);
//				int status = jsonObject.getInt("status");
//				if (status == 1) {
//					sp.edit().putLong("last_test_time_blood_presure", data.getDate()).commit();
//				}
//			} catch (JSONException e) {
//				e.printStackTrace();
//			}
//			return null;
//		}
//	}

	/**
	 * 像数据库增加数据。
	 */
	private void insertData(Float heartRate, Float highPressure, Float lowPressure, String State, String device_id, String hand_str, long date) {
		bloodPressureData = new BloodPressureData(null, heartRate, highPressure, lowPressure,userid, State, device_id, hand_str, date);
		System.out.println("这个是insert的时候    " + new Date(date));
		bloodPressureDataDao.insert(bloodPressureData);
//		uploadDataToServer(bloodPressureData.clone());
		bloodPressureData = null;

	}

	private void stoptest(byte[] value) {
		send_Characteristic.setValue(value);
		boolean isSuc = utils.writeCharacteristic(send_Characteristic);
		// Toast.makeText(getActivity(), "当前发送的命令的状态" + isSuc,
		// Toast.LENGTH_LONG)
		// .show();
		rece_Characteristic = getReceChar(swapDataService, CommonAttr.Sphygmomanometer.SERVICE_CHARACTERISTIC_RECEIVE);
	}

	private void starttest(byte[] value) {
		/* 避免出现获取不到当前设备通道出现崩溃。 */
		if (send_Characteristic == null) {
			Toast.makeText(getActivity(), "设备连接异常，请重新连接！", Toast.LENGTH_LONG).show();
			stateFail();
			return;
		}
		send_Characteristic.setValue(value);
		boolean isSuc = utils.writeCharacteristic(send_Characteristic);
		rece_Characteristic = getReceChar(swapDataService, CommonAttr.Sphygmomanometer.SERVICE_CHARACTERISTIC_RECEIVE);
		// Toast.makeText(getActivity(), "当前发送的命令的状态" + isSuc,
		// Toast.LENGTH_LONG)
		// .show();
	}

	boolean isGetResult = true;

	private void getResult(byte[] value) {
		if (send_Characteristic == null) {
			stateFail();
			return;
		}
		send_Characteristic.setValue(value);
		Log.d("BLOODPRESURE", "send_Characteristic.setValue(value);");
		boolean isSuc = utils.writeCharacteristic(send_Characteristic);
		if (isGetResult) {
			mHandler.sendEmptyMessageDelayed(0, 1000);
		}
	}

	private void getBattary(byte[] value) {
		send_Characteristic.setValue(value);
		boolean isSuc = utils.writeCharacteristic(send_Characteristic);
		rece_Characteristic = getReceChar(swapDataService, CommonAttr.Sphygmomanometer.SERVICE_CHARACTERISTIC_RECEIVE);
		Toast.makeText(getActivity(), "当前发送的命令的状态" + isSuc, Toast.LENGTH_LONG).show();
	}

	int i = 0;
	private WjkFragment wjkFragment;

	/**
	 * 获取需要操作的通道
	 */
	private void getGattCharacteristics() {
		swapDataService = utils.getGattService(CommonAttr.Sphygmomanometer.SERVICE_UUID);

		if (null == swapDataService) {
          System.out.println("swapDataService is nulllllllllll");
			return;

		}

		send_Characteristic = getSendChar(swapDataService, CommonAttr.Sphygmomanometer.SERVICE_CHARACTERISTIC_SEND);
		rece_Characteristic = getReceChar(swapDataService, CommonAttr.Sphygmomanometer.SERVICE_CHARACTERISTIC_RECEIVE);

	}

	public boolean read() {
		if (swapDataService != null && rece_Characteristic != null) {
			BluetoothGatt gatt = utils.getBluetoothGatt();
			boolean bool = gatt.readCharacteristic(rece_Characteristic);

			Log.e("mg", "send....write..." + bool);
			return bool;
		}
		return false;
	}

	public BluetoothGattCharacteristic getSendChar(BluetoothGattService service, String UUID) {

		BluetoothGattCharacteristic curChar = null;

		for (BluetoothGattCharacteristic chart : service.getCharacteristics()) {

			if (chart.getUuid().toString().equals(UUID)) {
				curChar = chart;
				connectPort(curChar);

			}
		}
		return curChar;
	}

	/**
	 * 选择当前的设备，并且监听；
	 * 
	 * @param service
	 * @param UUID
	 * @return
	 */
	public BluetoothGattCharacteristic getReceChar(BluetoothGattService service, String UUID) {

		BluetoothGattCharacteristic curChar = null;
		if (service == null || service.getCharacteristics() == null)
			return null;
		for (BluetoothGattCharacteristic chart : service.getCharacteristics()) {

			if (chart.getUuid().toString().equals(UUID)) {
				curChar = chart;
				connectPort(curChar);
			}
		}
		return curChar;
	}

	/**
	 * 设定当前的char，打开通道；
	 */
	private void connectPort(BluetoothGattCharacteristic gattCharacteristic) {
		utils.readCharacteristic(gattCharacteristic);
		utils.setCharacteristicNotification(gattCharacteristic, true);
	}

	/**
	 * 广播过滤器 蓝牙状态的处理
	 * 
	 * @return
	 */
	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_GATT_DISCONNECTED);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_READ_CHARACTERISTIC);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_SYSTEMID);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_XUEYA_DATA);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_WEIGHT_DATA);
		intentFilter.addAction(BLEBloodPresureProvider.ACTION_WRITE_DATA_AVAILABLE);
		return intentFilter;

	}

	public void setWJKfragment(WjkFragment fragment) {
		wjkFragment = fragment;
	}

	/**
	 * 设置页面是否自动连接
	 * 
	 * @param autoConnect
	 */
	public void setAutoConnect(boolean autoConnect) {
		this.aotuConnect = autoConnect;
	}

	boolean aotuConnect = false; // 进入页面是否自动连接

	/**
	 * 当前为打开蓝牙设备，
	 */
	private void unOpenBleTip() {
		final TipDialog dialog = new TipDialog(getActivity(), TipDialog.VIEW_TIP);
		dialog.setTitleAndContent("蓝牙未开启", "检测到你没有打开手机蓝牙，请打开后再试");
		dialog.setOkayCallback(new OkayListener() {

			@Override
			public void okay() {
				dialog.dismiss();
				Log.d(TAG, "用户未开启当前手机的蓝牙设备；");
			}
		});
		dialog.show();
	}

	public String getWjkAddcontent() {
		return wjkAddcontent;
	}

	public void setWjkAddcontent(String wjkAddcontent) {
		this.wjkAddcontent = wjkAddcontent;
	}

	/* 三中状态， 扫描ing， 连接suc， 连接fail */
	/** 扫描中 */
	public void stateScaning() {
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				tv_connect_state.setVisibility(View.GONE); // 隐藏连接状态
				hideLine();// 隐藏黄线
				dialog.show(); // 展示黄线
			}
		});

	}

	/** 连接成功 */
	public void stateSuc() {
		is_connect = false;
		Log.e("xueyasuccesssss---","save");
		ConnectedDevice bloodDevice = FileUtil.getBloodDevice();
		bloodDevice.setConnect_time(System.currentTimeMillis());
		bloodDevice.setConnected(true);
		FileUtil.saveBloodDevice(bloodDevice);
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				bpv.setTestResult("");
				mBloodConnectStatus = true;
				bpv.setBtnText("开始测量");
				bpv.setBtnState(true);
				tv_connect_state.setVisibility(View.VISIBLE);
				hideLine();// 隐藏黄线
				dialog.dismiss();
				upLoadDeviceToServer();
			}
		});

	}
	
	/**
	 * 上传到服务器
	 */
	private void upLoadDeviceToServer() {
		HashMap<Object, Object> map = new HashMap<Object, Object>();
		JSONObject json = new JSONObject();
		JSONArray array = new JSONArray();
		try {
			json.put("de_id", DeviceState.BLOOD_TYPE);
			json.put("de_string", DeviceState.BLOOD_DEVICENAME);
			json.put("e_number", MD5Util.md5(DeviceState.BLOOD_TYPE+DeviceState.BLOOD_DEVICENAME));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		map.put("equipment_datas", "[" + json.toString() + "]");
		map.put("xywy_userid", userid);
		System.out.println("[" + json.toString() + "]");
		System.out.println(userid);
		Request.postData(new StringParser(), upLoadCall, DeviceState.uploadDeviceUrl, map);
	}

	DataCallBack<String> upLoadCall = new DataCallBack<String>() {

		@Override
		public void dataCall(String t) {
			// TODO Auto-generated method stub
			if (t == null) {
				return;
			}
			System.out.println(t);
			try {
				JSONObject json = new JSONObject(t);
				JSONArray array = json.optJSONArray("data");
				if (array.length() == 0) {
					// 同步成功
				} else {
					// 同步时 不是最新 ？？？？

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/** 连接失败 */
	public void stateFail() {
		Log.e("xueyafailed---","save");
		is_connect = false;
		ConnectedDevice blood_device = FileUtil.getBloodDevice();
		blood_device.setConnected(false);
		FileUtil.saveBloodDevice(blood_device);
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (!FragmentMainActivity.CANTOUCH) {
					bpv.setHightAndLowNum(0, 0);
					bpv.setTestResult("测量失败,请重试");
				}
				bpv.setBtnText("开始测量");
				bpv.setBtnState(false);
				FragmentMainActivity.CANTOUCH = true;
				mBloodConnectStatus = false;
				tv_connect_state.setVisibility(View.GONE); // 隐藏连接状态
				showLine();// 隐藏黄线
				dialog.dismiss();
			}
		});

	}

	/**
	 * 隐藏当前的黄线
	 */
	public void hideLine() {
	    ll_not_connectted_prompot.setVisibility(View.GONE);
	}
	
	/**
	 * 展示当前的黄线
	 */
	public void showLine() {
	    ll_not_connectted_prompot.setVisibility(View.VISIBLE);
	}
	
	/**
	 * 获取最后一条数据
	 * 
	 * @return
	 */
	private List<BloodPressureData> getLastData() {
		QueryBuilder<BloodPressureData> qb = bloodPressureDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(userid));
		qb.orderDesc(Properties.Id);
		return qb.list();
	}

	/**
	 * 上传到服务器
	 */
//	private void upLoadDeviceToServer() {
//		HashMap<Object, Object> map = new HashMap<Object, Object>();
//		JSONObject json = new JSONObject();
//		JSONArray array = new JSONArray();
//		try {
//			json.put("de_id", DeviceState.BLOOD_TYPE);
//			json.put("de_string", DeviceState.BLOOD_DEVICENAME);
//			json.put("e_number", MD5Util.md5(DeviceState.BLOOD_TYPE+DeviceState.BLOOD_DEVICENAME));
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		}
//		map.put("equipment_datas", "[" + json.toString() + "]");
//		map.put("xywy_userid", userid);
//		System.out.println("[" + json.toString() + "]");
//		System.out.println(userid);
//		Request.postData(new StringParser(), upLoadCall, DeviceState.uploadDeviceUrl, map);
//	}
//
//	DataCallBack<String> upLoadCall = new DataCallBack<String>() {
//
//		@Override
//		public void dataCall(String t) {
//			// TODO Auto-generated method stub
//			if (t == null) {
//				return;
//			}
//			System.out.println(t);
//			try {
//				JSONObject json = new JSONObject(t);
//				JSONArray array = json.optJSONArray("data");
//				if (array.length() == 0) {
//					// 同步成功
//				} else {
//					// 同步时 不是最新 ？？？？
//
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	};

	
	private void initReceiver(){
		getActivity().registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		IntentFilter filter = new IntentFilter(WjkConstant.CONNECTING_BLOOD_ACTION);
		filter.addAction(WjkConstant.CONNECT_BLOOD_RESTART);
		getActivity().registerReceiver(new ChangeReceiver(), filter);
	}
	
	class ChangeReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(WjkConstant.CONNECTING_BLOOD_ACTION.equals(action)){
				System.out.println("现在开始血压的蓝牙连接----11111111111111111");
				scanLeDevice(true, "KBB");
			}else if (WjkConstant.CONNECT_BLOOD_RESTART.equals(action)) {
			    getActivity().runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						Toast.makeText(getActivity(), "请重启血压计", Toast.LENGTH_SHORT).show();
					    stateFail();
					}
				});
			}
		}
	}
	

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initReceiver();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(mBloodConnectStatus){
			if(WjkActivity.HOME_FLAG){
			}else {
				WjkActivity.HOME_FLAG = false;
				return;
			}
		}
		WjkActivity.HOME_FLAG = false;
		List<BloodPressureData> datas = getLastData();
		if (datas != null && datas.size() > 0) {
			messageTime.setVisibility(View.VISIBLE);
			BloodPressureData data = datas.get(0);
			long dataTime = data.getDate();
			String dt = dataTime + "";

			if (dt.length() == 10) {
				dataTime *= 1000;
			}
//			if (!mBloodConnectStatus) {
//				messageTime.setText(CalendarUtil.getDiffTime(dataTime));
//				if(data.getHighPressure()>0 && data.getLowPressure()>0)
//				bpv.setTestResult(BloodPresureCommon.getTestResult(data.getHighPressure(), data.getLowPressure()));
//			}
		} else {
//			messageTime.setVisibility(View.INVISIBLE);
		}
	}
}